'use strict';

const Service = require('egg').Service;

// 数据库操作
class UserService extends Service {
    async user() {
        const { ctx, app } = this;
        const QUERY_STR = 'id, name';
        let sql = "SELECT " + QUERY_STR+" FROM `userList`"; // 获取 id 的 sql 语句
        try {
            console.log(app);
            const result = await app.mysql.query(sql); // mysql 实例已经挂载到 app 对象下，可以通过 app.mysql 获取到。
            return result;
        } catch (error) {
            return null;
        }
    }
    async addUser(user_name) {
        const { ctx,app } = this;
        try{
            const result = await app.mysql.insert('userList',{user_name});
            return result
        }catch (e) {
            return null;
        }
    }
    // 编辑
    async editUser(id, user_name) {
        const { ctx, app } = this;
        try {
            let result = await app.mysql.update('userList', { user_name }, {
                where: {
                    id
                }
            });
            return result;
        } catch (error) {
            console.log(error);
            return null;
        }
    }
    // 删除
    async deleteUser(id) {
        const { ctx, app } = this;
        try {
            let result = await app.mysql.delete('userList', { id });
            return result;
        } catch (error) {
            console.log(error);
            return null;
        }
    }

    // 通过用户名获取用户信息
    async getUserByName(user_name) {
        const { app } = this;
        try {
            const result = await app.mysql.get('userList', { user_name });
            return result;
        } catch (error) {
            console.log(error);
            return null;
        }
    }

    // 注册
    async register(params) {
        const { app } = this;
        try {
            const result = await app.mysql.insert('userList', params);
            return result;
        } catch (error) {
            console.log(error);
            return null;
        }
    }
}
module.exports = UserService;